package com.tlgen.orm.utils.reflect;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.tlgen.orm.annotation.AsNotField;
import com.tlgen.orm.annotation.Association;
import com.tlgen.orm.annotation.Collection;
import com.tlgen.orm.components.rest.model.RequestMethodAndUrl;
import com.tlgen.orm.param.FieldParam;
import com.tlgen.orm.support.lambda.TypeFunction;
import com.tlgen.orm.utils.ClassesUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 反射工具类
 */
@Slf4j
public class ReflectionUtils {

    // 方法签名缓存
    private static final ConcurrentHashMap<String, MethodHandle> METHOD_CACHE = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<Class<?>, Constructor<?>> CONSTRUCTOR_CACHE = new ConcurrentHashMap<>();

    // 排除作为数据库字段映射的注解
    private static final Class<? extends Annotation>[] EXCLUDE_FIELD_MAPPING_ANNOTATIONS =
            new Class[]{AsNotField.class, Association.class, Collection.class};

    // 执行反射方法
    public static Object invokeHttpRequest(RequestMethodAndUrl request) {
        final String className = request.getClassName();
        final String methodName = request.getMethodName();

        // 修复1: 提取FieldParam的实际值而不是传递整个对象
        final Object[] rawArgs = extractFieldParamValues(request.getArgs()); // 新的辅助方法

        try {
            // 1. 加载目标类
            Class<?> targetClass = Class.forName(className, true, Thread.currentThread().getContextClassLoader());

            // 2. 处理接口实现
            if (targetClass.isInterface()) {
                targetClass = ClassesUtils.getImplClassesTypeByInterfaceClassName(className);
            }

            // 转换为不可变变量用于lambda
            final Class<?> finalTargetClass = targetClass;

            // 3. 获取实例（使用缓存）
            Object instance = getOrCreateInstance(targetClass);

            // 4. 获取方法句柄（使用缓存）
            String methodSignature = buildMethodSignature(finalTargetClass, methodName, rawArgs);
            MethodHandle methodHandle = METHOD_CACHE.computeIfAbsent(methodSignature,
                    k -> resolveMethodHandle(finalTargetClass, methodName, rawArgs));

            // 5. 准备参数
            Object[] args = prepareArguments(rawArgs, methodHandle.type().parameterList());

            // 6. 类型安全调用
            return methodHandle.invokeWithArguments(prepareInvokeArguments(instance, args));

        } catch (NoSuchMethodException e) {
            // 方法不存在时抛出特定异常
            throw new RuntimeException("No compatible method found: " + methodName, e);
        } catch (Throwable e) {
            // 将其他错误转换为运行时异常
            throw new RuntimeException("Method call failed: " + methodName, e);
        }
    }

    /**
     * 新增方法：从FieldParam数组中提取实际值
     */
    public static Object[] extractFieldParamValues(Object[] rawArgs) {
        if (rawArgs == null || rawArgs.length == 0) {
            return new Object[0];
        }

        List<Object> values = new ArrayList<>();
        for (Object arg : rawArgs) {
            if (arg instanceof FieldParam) {
                // 提取FieldParam的实际值
                values.add(((FieldParam) arg).getValue());
            } else {
                // 处理非FieldParam参数
                values.add(arg);
            }
        }
        return values.toArray();
    }

    /**
     * 准备调用参数（修复类型转换问题）
     */
    private static Object[] prepareArguments(Object[] rawArgs, List<Class<?>> paramTypes) {
        if (rawArgs == null || rawArgs.length == 0) {
            return new Object[0];
        }

        Object[] preparedArgs = new Object[rawArgs.length];

        for (int i = 0; i < rawArgs.length && i < paramTypes.size() - 1; i++) {
            Class<?> targetType = paramTypes.get(i + 1); // 跳过第一个instance参数

            // 类型匹配无需转换
            if (rawArgs[i] != null && targetType.isAssignableFrom(rawArgs[i].getClass())) {
                preparedArgs[i] = rawArgs[i];
                continue;
            }

            // 复杂类型转换（特别是对象类型）
            preparedArgs[i] = convertArgument(rawArgs[i], targetType);
        }

        return preparedArgs;
    }

    /**
     * 准备方法调用参数数组
     */
    private static Object[] prepareInvokeArguments(Object instance, Object[] args) {
        if (args == null || args.length == 0) {
            return new Object[]{instance};
        }

        Object[] invokeArgs = new Object[args.length + 1];
        invokeArgs[0] = instance;
        System.arraycopy(args, 0, invokeArgs, 1, args.length);
        return invokeArgs;
    }

    /**
     * 智能参数转换（解决 SysUser 转换问题）
     */
    private static Object convertArgument(Object rawValue, Class<?> targetType) {
        if (rawValue == null) {
            return null;
        }

        // 1. 字符串转自定义对象
        if (rawValue instanceof String && !isPrimitiveOrWrapper(targetType) && !targetType.isEnum()) {
            try {
                return JSON.parseObject((String) rawValue, targetType);
            } catch (Exception e) {
                // 不是JSON格式，尝试其他转换
            }
        }

        // 2. Map转对象
        if (rawValue instanceof Map) {
            try {
                return JSON.parseObject(JSON.toJSONString(rawValue), targetType);
            } catch (Exception e) {
                // 转换失败
            }
        }

        // 3. 基本类型转换
        if (rawValue instanceof String) {
            return convertPrimitive((String) rawValue, targetType);
        }

        // 4. 数组类型处理
        if (targetType.isArray()) {
            return convertToArray(rawValue, targetType);
        }

        return rawValue; // 无法转换则返回原值
    }

    /**
     * 判断是否为基本类型或包装类
     */
    private static boolean isPrimitiveOrWrapper(Class<?> clazz) {
        return clazz.isPrimitive() ||
                clazz == Byte.class ||
                clazz == Short.class ||
                clazz == Integer.class ||
                clazz == Long.class ||
                clazz == Float.class ||
                clazz == Double.class ||
                clazz == Boolean.class ||
                clazz == Character.class;
    }

    /**
     * 数组类型转换
     */
    private static Object convertToArray(Object rawValue, Class<?> arrayType) {
        Class<?> componentType = arrayType.getComponentType();

        // JSON格式数组
        if (rawValue instanceof String) {
            try {
                return JSON.parseArray((String) rawValue, componentType).toArray();
            } catch (Exception e) {
                // 不是JSON格式
            }
        }

        // 列表转数组
        if (rawValue instanceof List) {
            List<?> list = (List<?>) rawValue;
            Object array = Array.newInstance(componentType, list.size());
            for (int i = 0; i < list.size(); i++) {
                Array.set(array, i, list.get(i));
            }
            return array;
        }

        return rawValue;
    }

    /**
     * 解析方法句柄
     */
    private static MethodHandle resolveMethodHandle(Class<?> clazz, String methodName, Object[] args) {
        try {
            // 根据参数类型查找最佳匹配
            MethodHandles.Lookup lookup = MethodHandles.lookup();

            for (Method method : clazz.getDeclaredMethods()) {
                if (!method.getName().equals(methodName)) continue;

                Class<?>[] paramTypes = method.getParameterTypes();

                // 检查参数兼容性
                if (isCompatible(args, paramTypes)) {
                    method.setAccessible(true);
                    return lookup.unreflect(method);
                }
            }

            throw new NoSuchMethodException("No compatible method found: " + methodName);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse method handle: ", e);
        }
    }

    /**
     * 检查参数兼容性
     */
    private static boolean isCompatible(Object[] args, Class<?>[] paramTypes) {
        if (args == null) return paramTypes.length == 0;
        if (args.length != paramTypes.length) return false;

        for (int i = 0; i < args.length; i++) {
            if (args[i] == null) {
                if (paramTypes[i].isPrimitive()) return false;
            } else if (!isConvertible(args[i].getClass(), paramTypes[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查类型可转换性
     */
    private static boolean isConvertible(Class<?> from, Class<?> to) {
        // 相同类型直接兼容
        if (to.isAssignableFrom(from)) return true;

        // 检查基本类型兼容性
        if (from == String.class && isPrimitiveOrWrapper(to)) return true;

        // 对象类型转换
        if (from == String.class && !to.isPrimitive()) return true;

        return false;
    }

    /**
     * 构建方法签名
     */
    private static String buildMethodSignature(Class<?> clazz, String methodName, Object[] args) {
        StringBuilder sb = new StringBuilder(128);
        sb.append(clazz.getName()).append('#').append(methodName);

        if (args != null) {
            sb.append('[');
            for (Object arg : args) {
                if (arg != null) {
                    sb.append(arg.getClass().getSimpleName()).append(',');
                } else {
                    sb.append("null,");
                }
            }
            if (args.length > 0) sb.setLength(sb.length() - 1); // 移除末尾逗号
            sb.append(']');
        }
        return sb.toString();
    }

    /**
     * 获取或创建实例
     */
    private static Object getOrCreateInstance(Class<?> clazz) throws Exception {
        Constructor<?> constructor = CONSTRUCTOR_CACHE.get(clazz);
        if (constructor == null) {
            constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(true);
            CONSTRUCTOR_CACHE.put(clazz, constructor);
        }
        return constructor.newInstance();
    }

    /**
     * 基本类型转换
     */
    private static Object convertPrimitive(String value, Class<?> targetType) {
        try {
            if (targetType == int.class || targetType == Integer.class) {
                return Integer.parseInt(value);
            } else if (targetType == long.class || targetType == Long.class) {
                return Long.parseLong(value);
            } else if (targetType == double.class || targetType == Double.class) {
                return Double.parseDouble(value);
            } else if (targetType == float.class || targetType == Float.class) {
                return Float.parseFloat(value);
            } else if (targetType == boolean.class || targetType == Boolean.class) {
                return Boolean.parseBoolean(value);
            } else if (targetType == byte.class || targetType == Byte.class) {
                return Byte.parseByte(value);
            } else if (targetType == short.class || targetType == Short.class) {
                return Short.parseShort(value);
            } else if (targetType == char.class || targetType == Character.class) {
                return value.charAt(0);
            }
        } catch (NumberFormatException e) {
            return getDefaultValue(targetType);
        }
        return value;
    }

    /**
     * 获取默认值
     */
    private static Object getDefaultValue(Class<?> type) {
        if (type == byte.class) return (byte) 0;
        if (type == short.class) return (short) 0;
        if (type == int.class) return 0;
        if (type == long.class) return 0L;
        if (type == float.class) return 0f;
        if (type == double.class) return 0d;
        if (type == boolean.class) return false;
        if (type == char.class) return '\0';
        return null;
    }

    public static Map<String, Object> getObjectFieldValues(Object object) {
        Map<String, Object> map = Maps.newHashMap();
        Class<?> aClass = object.getClass();
        for (Field declaredField : aClass.getDeclaredFields()) {
            declaredField.setAccessible(true);
            Object value = null;
            try {
                value = declaredField.get(object);
            } catch (IllegalAccessException ignored) {
            }
            map.put(declaredField.getName(), value);
        }
        return map;
    }

    /**
     * 获取已有对象的属性值
     *
     * @param obj
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Object obj, String fieldName) {
        // 1.根据属性名称就可以获取其get方法
        String getMethodName = "get"
                + fieldName.substring(0, 1).toUpperCase()
                + fieldName.substring(1);
        try {
            // get 方法都是 public 的且无参数
            Method m = obj.getClass().getMethod(getMethodName);
            //3 通过方法的反射操作方法
            Object value = m.invoke(obj);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将 bean 的属性的 get 方法, 作为 lambda 表达式传入时, 获取 get 方法对应的属性 Field
     *
     * @param fn  lambda 表达式, bean 的属性的 get 方法
     * @param <T> 泛型
     * @return 属性对象
     */
    public static <T> String getLambdaFieldName(TypeFunction<T, ?> fn) {
        // 从function取出序列化方法
        Method writeReplaceMethod;
        try {
            writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace");
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 从序列化方法取出序列化的lambda信息
        boolean isAccessible = writeReplaceMethod.isAccessible();
        writeReplaceMethod.setAccessible(true);
        SerializedLambda serializedLambda;
        try {
            serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(fn);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        writeReplaceMethod.setAccessible(isAccessible);

        // 从lambda信息取出method、field、class等
        String implMethodName = serializedLambda.getImplMethodName();
        // 确保方法是符合规范的get方法，boolean类型是is开头
        if (!implMethodName.startsWith("is") && !implMethodName.startsWith("get")) {
            throw new RuntimeException("get 方法名称: " + implMethodName + ", 不符合 java bean 规范");
        }

        // get方法开头为 is 或者 get，将方法名 去除is或者get，然后首字母小写，就是属性名
        int prefixLen = implMethodName.startsWith("is") ? 2 : 3;

        String fieldName = implMethodName.substring(prefixLen);
        String firstChar = fieldName.substring(0, 1);
        fieldName = fieldName.replaceFirst(firstChar, firstChar.toLowerCase());
        Field field;
        try {
            field = Class.forName(serializedLambda.getImplClass().replace("/", ".")).getDeclaredField(fieldName);
        } catch (ClassNotFoundException | NoSuchFieldException e) {
            throw new RuntimeException(e);
        }

        return field.getName();
    }

    /**
     * 为对象指定属性赋值(支持类型转换和递归查找)
     *
     * @param object     目标对象
     * @param fieldName  字段名
     * @param fieldValue 字段值
     */
    public static void setFieldValue(Object object, String fieldName, Object fieldValue) {
        if (object == null || fieldName == null) {
            return;
        }

        try {
            // 递归查找字段(包括父类)
            Field field = findFieldRecursive(object.getClass(), fieldName);
            if (field == null) {
                throw new NoSuchFieldException("Field not found: " + fieldName);
            }

            // 检查字段是否可访问
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }

            // 检查并转换值类型
            Object convertedValue = convertValue(field.getType(), fieldValue);

            // 设置字段值
            field.set(object, convertedValue);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // 记录错误或抛出运行时异常
            throw new RuntimeException("Failed to set field value: " + fieldName, e);
        }
    }

    /**
     * 递归查找字段(包括所有父类)
     */
    private static Field findFieldRecursive(Class<?> clazz, String fieldName) {
        Class<?> current = clazz;
        while (current != null && current != Object.class) {
            try {
                return current.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                // 继续在父类中查找
                current = current.getSuperclass();
            }
        }
        return null;
    }

    /**
     * 转换值到目标类型
     */
    private static Object convertValue(Class<?> targetType, Object value) {
        if (value == null) {
            return null;
        }

        // 如果类型匹配，直接返回
        if (targetType.isAssignableFrom(value.getClass())) {
            return value;
        }

        // 处理基本类型和包装类型
        if (targetType.isPrimitive()) {
            return convertPrimitiveValue(targetType, value);
        }

        // 处理常见类型转换
        if (targetType == String.class) {
            return value.toString();
        }

        // 处理数字类型转换
        if (Number.class.isAssignableFrom(targetType) && value instanceof Number) {
            return convertNumberValue(targetType, (Number) value);
        }

        // 处理枚举类型
        if (targetType.isEnum()) {
            return convertEnumValue(targetType, value);
        }

        // 处理布尔类型
        if (targetType == Boolean.class || targetType == boolean.class) {
            return convertBooleanValue(value);
        }

        // 无法转换，抛出异常
        throw new IllegalArgumentException(String.format(
                "Cannot convert value of type %s to field type %s",
                value.getClass().getName(), targetType.getName()
        ));
    }

    /**
     * 转换基本类型值
     */
    private static Object convertPrimitiveValue(Class<?> targetType, Object value) {
        if (targetType == int.class) {
            return toInt(value);
        } else if (targetType == long.class) {
            return toLong(value);
        } else if (targetType == double.class) {
            return toDouble(value);
        } else if (targetType == float.class) {
            return toFloat(value);
        } else if (targetType == boolean.class) {
            return toBoolean(value);
        } else if (targetType == char.class) {
            return toChar(value);
        } else if (targetType == byte.class) {
            return toByte(value);
        } else if (targetType == short.class) {
            return toShort(value);
        }
        throw new IllegalArgumentException("Unsupported primitive type: " + targetType);
    }

    /**
     * 转换数字类型值
     */
    private static Object convertNumberValue(Class<?> targetType, Number value) {
        if (targetType == Integer.class || targetType == int.class) {
            return value.intValue();
        } else if (targetType == Long.class || targetType == long.class) {
            return value.longValue();
        } else if (targetType == Double.class || targetType == double.class) {
            return value.doubleValue();
        } else if (targetType == Float.class || targetType == float.class) {
            return value.floatValue();
        } else if (targetType == Byte.class || targetType == byte.class) {
            return value.byteValue();
        } else if (targetType == Short.class || targetType == short.class) {
            return value.shortValue();
        }
        throw new IllegalArgumentException("Unsupported number type: " + targetType);
    }

    /**
     * 转换枚举值
     */
    private static Object convertEnumValue(Class<?> targetType, Object value) {
        if (value instanceof String) {
            // 通过名称查找枚举
            return Enum.valueOf((Class<Enum>) targetType, (String) value);
        } else if (value instanceof Number) {
            // 通过序号查找枚举
            int ordinal = ((Number) value).intValue();
            Enum<?>[] enums = (Enum<?>[]) targetType.getEnumConstants();
            if (ordinal >= 0 && ordinal < enums.length) {
                return enums[ordinal];
            }
        }
        throw new IllegalArgumentException("Cannot convert to enum: " + value);
    }

    /**
     * 转换布尔值
     */
    private static Object convertBooleanValue(Object value) {
        if (value instanceof Boolean) {
            return value;
        } else if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        } else if (value instanceof String) {
            String str = ((String) value).toLowerCase();
            return "true".equals(str) || "1".equals(str) || "yes".equals(str);
        }
        return false;
    }

    // ==================== 类型转换工具方法 ====================

    private static int toInt(Object value) {
        if (value instanceof Number) {
            return ((Number) value).intValue();
        } else if (value instanceof String) {
            return Integer.parseInt((String) value);
        } else if (value instanceof Boolean) {
            return ((Boolean) value) ? 1 : 0;
        }
        throw new IllegalArgumentException("Cannot convert to int: " + value);
    }

    private static long toLong(Object value) {
        if (value instanceof Number) {
            return ((Number) value).longValue();
        } else if (value instanceof String) {
            return Long.parseLong((String) value);
        }
        throw new IllegalArgumentException("Cannot convert to long: " + value);
    }

    private static double toDouble(Object value) {
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        } else if (value instanceof String) {
            return Double.parseDouble((String) value);
        }
        throw new IllegalArgumentException("Cannot convert to double: " + value);
    }

    private static float toFloat(Object value) {
        if (value instanceof Number) {
            return ((Number) value).floatValue();
        } else if (value instanceof String) {
            return Float.parseFloat((String) value);
        }
        throw new IllegalArgumentException("Cannot convert to float: " + value);
    }

    private static boolean toBoolean(Object value) {
        if (value instanceof Boolean) {
            return (Boolean) value;
        } else if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        } else if (value instanceof String) {
            String str = ((String) value).toLowerCase();
            return "true".equals(str) || "1".equals(str) || "yes".equals(str);
        }
        return false;
    }

    private static char toChar(Object value) {
        if (value instanceof Character) {
            return (Character) value;
        } else if (value instanceof Number) {
            return (char) ((Number) value).intValue();
        } else if (value instanceof String && ((String) value).length() > 0) {
            return ((String) value).charAt(0);
        }
        throw new IllegalArgumentException("Cannot convert to char: " + value);
    }

    private static byte toByte(Object value) {
        if (value instanceof Number) {
            return ((Number) value).byteValue();
        } else if (value instanceof String) {
            return Byte.parseByte((String) value);
        }
        throw new IllegalArgumentException("Cannot convert to byte: " + value);
    }

    private static short toShort(Object value) {
        if (value instanceof Number) {
            return ((Number) value).shortValue();
        } else if (value instanceof String) {
            return Short.parseShort((String) value);
        }
        throw new IllegalArgumentException("Cannot convert to short: " + value);
    }

    public static List<String> getFields(String completeClassName) {
        try {
            Class<?> clazz = Class.forName(completeClassName);
            return getFieldsRecursively(clazz);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private static List<String> getFieldsRecursively(Class<?> clazz) {
        List<String> fieldList = new ArrayList<>();

        // 递归基类 - 当类为Object或null时停止
        if (clazz == null || clazz == Object.class) {
            return fieldList;
        }

        // 首先递归处理父类（深度优先）
        if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) {
            fieldList.addAll(getFieldsRecursively(clazz.getSuperclass()));
        }

        // 处理当前类的字段
        for (Field field : clazz.getDeclaredFields()) {
            // 跳过静态字段
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            // 检查是否应该排除该字段
            boolean shouldExclude = false;
            for (Class<? extends Annotation> annotationClass : EXCLUDE_FIELD_MAPPING_ANNOTATIONS) {
                if (field.isAnnotationPresent(annotationClass)) {
                    shouldExclude = true;
                    break;
                }
            }

            if (!shouldExclude) {
                fieldList.add(field.getName());
            }
        }

        return fieldList;
    }

    public static Class<?> getClassByCompleteClassName(String completeClassName) {
        Class<?> aClass = null;
        try {
            aClass = Class.forName(completeClassName);
        } catch (ClassNotFoundException e) {
            log.error("Class not found: {}", completeClassName);
        }
        return aClass;
    }

    public static Object fieldParamsToObject(List<FieldParam> fieldParams, String completeClassName) {
        if (Objects.nonNull(completeClassName)) {
            Object object;
            try {
                Class<?> aClass = Class.forName(completeClassName);
                object = aClass.newInstance();
                Field[] fields = aClass.getDeclaredFields();
                for (Field field : fields) {
                    fieldParams.forEach(x -> {
                        if (Objects.equals(x.getName(), field.getName())) {
                            field.setAccessible(true);
                            try {
                                field.set(object, doFormatType(field.getType(), x.getValue()));
                            } catch (IllegalAccessException ignored) {
                            }
                        }
                    });
                }
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            return object;
        }
        return null;
    }

    /**
     * 格式化属性, 设置正确的数据值类型
     *
     * @param fieldType
     * @param value
     * @return
     */
    private static Object doFormatType(Class<?> fieldType, Object value) {
        if (Objects.equals(fieldType.getTypeName(), Byte.class.getTypeName())) {
            value = Byte.valueOf(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), byte.class.getTypeName())) {
            value = Byte.parseByte(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), Short.class.getTypeName())) {
            value = Short.valueOf(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), short.class.getTypeName())) {
            value = Short.parseShort(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), Integer.class.getTypeName())) {
            value = Integer.valueOf(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), int.class.getTypeName())) {
            if (Objects.isNull(value)) {
                value = 0;
            } else {
                value = Integer.parseInt(String.valueOf(value));
            }
        }
        if (Objects.equals(fieldType.getTypeName(), Long.class.getTypeName())) {
            value = Long.valueOf(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), long.class.getTypeName())) {
            value = Long.parseLong(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), Float.class.getTypeName())) {
            value = Float.valueOf(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), float.class.getTypeName())) {
            value = Float.parseFloat(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), Double.class.getTypeName())) {
            value = Double.valueOf(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), double.class.getTypeName())) {
            value = Double.parseDouble(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), Boolean.class.getTypeName())) {
            value = Boolean.valueOf(String.valueOf(value));
        }
        if (Objects.equals(fieldType.getTypeName(), boolean.class.getTypeName())) {
            if (Objects.isNull(value)) {
                value = 0;
            } else {
                value = Boolean.parseBoolean(String.valueOf(value));
            }
        }
        return value;
    }

}
